import { setToken, getToken } from '@/utils/auth'
import { login, getProfile } from '@/api/user'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  }
}
const actions = {
  async login(context, payload) {
    // console.log('login', context, payload)
    const result = await login(payload)
    const token = result.data
    context.commit('setToken', token)
  },
  async getProfile(context) {
    const result = await getProfile()
    // console.log(result)
    // 调用mutations
    context.commit('setUserInfo', result.data)
    return result.data
  },
  logout(context) {
    // 退出登录
    // 清空token和userinfo
    context.commit('setToken', '')
    context.commit('setUserInfo', '')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
